using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace CodingDojo.Domain.KataRomanNumerals
{
  public class RomanNumerals : IRomanNumerals
  {
    public string IntegerToRoman(int number)
    {
      if (number < 1 || number > 3000)
        return "the number must be between 1 and 3000";

      var sequence = number.ToString(CultureInfo.InvariantCulture).Select(e => int.Parse(e.ToString(CultureInfo.InvariantCulture))).ToArray();
      var roman = string.Empty;

      for (var i = 0; i < sequence.Length; i++)
      {
        roman = string.Format("{0}{1}", roman, GetPart(Convert.ToInt32(sequence[i]), sequence.Length - i));
      }
      return roman;
    }

    private static string GetPart(int number, int index)
    {
      var vocabulary = new Dictionary<int, string[]>();
      vocabulary.Add(1, new[] { "I", "V", "X" });
      vocabulary.Add(2, new[] { "X", "L", "C" });
      vocabulary.Add(3, new[] { "C", "D", "M" });
      vocabulary.Add(4, new[] { "M", string.Empty, string.Empty });

      var roman = string.Empty;
      if (number == 9)
      {
        roman = vocabulary.First(e => e.Key == index).Value[2]; //"X"
        number = number - 10;
      }
      if (number >= 4)
      {
        roman = vocabulary.First(e => e.Key == index).Value[1]; //"V"
        number = number - 5;
      }
      if (number > 0 && number < 4)
      {
        for (var i = 0; i < number; i++)
          roman = string.Format("{0}{1}", roman, vocabulary.First(e => e.Key == index).Value[0]); //"I"
      }
      if (number == -1)
        roman = string.Format("{1}{0}", roman, vocabulary.First(e => e.Key == index).Value[0]); //"I"
      return roman;
    }
  }
}
